<script setup>
import { ref, watch } from 'vue'
import { avatarColor } from '@/assets/data/index.js'
import { uploadAPI } from '@/api/common'
import ImgCutter from 'vue-img-cutter'

const props = defineProps({
  url: {
    type: String,
    default: '-1'
  }
})

// 裁剪图片
const avatar = ref(props.url)
const imgFile = ref(null)
const onCutDownImg = (res) => {
  // 1.获取文件
  const file = res.file
  imgFile.value = file
  // 2.创建FileReader
  const reader = new FileReader()
  reader.onload = (e) => {
    avatar.value = e.target.result
  }
  reader.readAsDataURL(file)
}
watch(
  () => props.url,
  () => {
    avatar.value = props.url
  }
)

// 获取图片链接
const getImgUrl = async () => {
  // 头像是否修改过
  if (avatar.value === '-1') return ''
  if (avatar.value === props.url) return props.url

  // 上传头像
  const formdata = new FormData()
  formdata.append('file', imgFile.value)
  const url = await uploadAPI(formdata)
  return url
}
// 重置图片
const reset = () => {
  avatar.value = '-1'
}

defineExpose({ getImgUrl, reset })
</script>

<template>
  <div class="zy-upload-avatar">
    <!-- 判断头像是否有效 -->
    <svg-icon class="avatar" v-if="avatar === '-1'" icon-name="def_avatar" />
    <el-image
      class="avatar"
      v-else-if="avatar?.startsWith('http') || avatar?.startsWith('data:')"
      :src="avatar"
      fit="cover"
    >
      <template #error>
        <div class="image-slot">
          <el-icon><Picture /></el-icon>
        </div>
      </template>
    </el-image>
    <div class="avatar" v-else :style="{ backgroundImage: avatarColor[avatar] }"></div>
    <!-- 头像裁剪 -->
    <img-cutter
      ref="imgCutterModal"
      @cutDown="onCutDownImg"
      :boxWidth="700"
      :boxHeight="458"
      :cutWidth="240"
      :cutHeight="240"
    >
      <template #open>
        <div class="mask">
          <svg-icon class="change-icon" icon-name="qiehuan" />
        </div>
      </template>
    </img-cutter>
  </div>
</template>

<style lang="scss" scoped>
.zy-upload-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
  cursor: pointer;

  .avatar {
    width: 100%;
    height: 100%;
  }

  .mask {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;

    .change-icon {
      font-size: 22px;
      color: #fff;
    }
  }

  &:hover .mask {
    opacity: 1;
  }
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
}
</style>
